const fs = require('fs-extra');
const path = require('path');
const prompts = require('prompts');
const chalk = require('chalk');

const CONFIG_FILE = path.join(process.env.HOME || process.env.USERPROFILE, '.simple-tools', 'config.json');

async function ensureConfigDir() {
  const configDir = path.dirname(CONFIG_FILE);
  await fs.ensureDir(configDir);
}

async function saveToken(token) {
  await ensureConfigDir();
  await fs.writeJson(CONFIG_FILE, { token }, { spaces: 2 });
}

async function getToken() {
  try {
    if (await fs.pathExists(CONFIG_FILE)) {
      const config = await fs.readJson(CONFIG_FILE);
      return config.token;
    }
  } catch (err) {
    // 忽略错误
  }
  return null;
}

async function login() {
  const questions = [
    {
      type: 'text',
      name: 'username',
      message: '请输入用户名',
      validate: value => value.length > 0 ? true : '用户名不能为空'
    },
    {
      type: 'password',
      name: 'password',
      message: '请输入密码',
      validate: value => value.length > 0 ? true : '密码不能为空'
    }
  ];

  try {
    const response = await prompts(questions);
    
    // TODO: 这里需要替换为实际的登录 API 调用
    // 示例实现
    if (response.username && response.password) {
      const token = 'dummy-token-' + Date.now(); // 这里应该是从服务器获取的真实 token
      await saveToken(token);
      console.log(chalk.green('登录成功！'));
      return token;
    }
  } catch (err) {
    console.error(chalk.red('登录失败:'), err.message);
    throw err;
  }
}

async function checkLogin() {
  const token = await getToken();
  if (!token) {
    console.log(chalk.yellow('请先登录后再操作'));
    console.log(`运行 ${chalk.cyan('sits login')} 进行登录`);
    process.exit(1);
  }
  return token;
}

module.exports = {
  login,
  checkLogin,
  getToken
}; 